package com.hmall.order.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmall.common.api.ItemFeignClient;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.OrderDetailService;
import com.hmall.order.service.impl.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
@Slf4j
@Component
public class DelayListener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ItemFeignClient itemFeignClient;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 监听延迟消息队列
     */
    @RabbitListener(queues = "delayQueue")
    @Transactional
    public void listenDelayQueue(String orderId) {
        log.info("延迟消息队列收到消息：" + orderId);
        //根据id查询订单
        Order order = orderService.getById(orderId);
        if (order == null) {
            return;
        }
        //判断订单状态是否为未支付
        if (order.getStatus() != 1) {
            return;
        }
        //修改订单状态为已取消
        order.setStatus(5);
        order.setUpdateTime(new Date());
        orderService.updateById(order);
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, orderId);
        OrderDetail orderDetail = orderDetailService.getOne(queryWrapper);
        if (orderDetail == null) {
            return;
        }
        Integer num = orderDetail.getNum();
        itemFeignClient.recoverStock(orderDetail.getItemId(), num);
    }
}

